// Fill out your copyright notice in the Description page of Project Settings.


#include "DestinyHttpActionBase.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"


UDestinyHttpActionBase* UDestinyHttpActionBase::HttpRequest(FString Url, FString Data)
{
	UDestinyHttpActionBase* NewAab = NewObject<UDestinyHttpActionBase>();
	NewAab->TempUrl = Url;
	NewAab->TempData = Data;
	return NewAab;
}

void UDestinyHttpActionBase::Activate()
{
	const FDResponsDeleget TempOnReqSuccess = OnReqSuccess;
	const FDResponsDeleget TempOnReqFail = OnReqFail;
	FHttpModule& httpModule = FHttpModule::Get();
	TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpReq  = httpModule.CreateRequest();
	HttpReq->SetVerb(TEXT("GET"));
	HttpReq->SetHeader(TEXT("Content-Type"), TEXT("application/json;charset=UTF-8"));
	if(!TempData.IsEmpty())
	{
		FString ReqData = "data="+TempData;
		HttpReq->SetContentAsString(ReqData);
	}
	HttpReq->SetURL(TempUrl);
	HttpReq->OnProcessRequestComplete().BindLambda(
	 [TempOnReqSuccess,TempOnReqFail](
		 FHttpRequestPtr pRequest,
		 FHttpResponsePtr pResponse,
		 bool connectedSuccessfully) mutable {
	 if (connectedSuccessfully) {
		 FString RepData = pResponse->GetContentAsString();
		 TempOnReqSuccess.Broadcast(RepData);
	 } else {
		 switch (pRequest->GetStatus()) {
		 case EHttpRequestStatus::Failed_ConnectionError:
		 	UE_LOG(LogTemp, Error, TEXT("Connection error."));
			 TempOnReqFail.Broadcast("Connection error");
		 default:
		 	UE_LOG(LogTemp, Error, TEXT("req error."));
			 TempOnReqFail.Broadcast("error");
		 }
	 }
 });
	HttpReq->ProcessRequest();
}
